import hashlib,base64,random,string,requests,json
from application import app
class MemberService():

    @staticmethod
    def geneAuthCode(member_info=None):
        m = hashlib.md5()
        # 传一个实体user
        str ="%s-%s-%s" %(member_info.id,member_info.salt,member_info.status)
        # str加密,encode将其转换成我们的字节码
        m.update(str.encode("utf-8"))
        # m将其转换成16进制的编码
        return m.hexdigest()

    @staticmethod
    def geneSalt(length=16):
        keylist = [random.choice((string.ascii_letters + string.digits)) for i in range(length)]
        return ("".join(keylist))

    @staticmethod
    def getWechatOpenId(code):
        # url地址中的变量有 appid(APPID) 和app_key(SECRET)
        url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code" \
            .format(app.config['MINA_APP']['appid'], app.config['MINA_APP']['appkey'], code)
        # 为了在python中快送发送一个请求出去，我们需要安装一个扩展requests:pip install requests
        r = requests.get(url)
        # 将r中字符串转换成json字典
        res = json.loads(r.text)

        openid=None
        if 'openid' in res:
            # 在json中获取openid
            openid = res['openid']
        return openid

